<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="nickName">
        <el-input
          style="width: 160px"
          v-model="queryParams.nickName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="deptId">
        <el-select placeholder="请选择部门名称" v-model="queryParams.deptId" clearable style="width: 180px">
          <el-option
            v-for="item in allDept"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-promotion"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['publisher:task:add']"
        >发布
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['publisher:task:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['publisher:task:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['publisher:task:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户名称" align="center" prop="nickName"/>
      <el-table-column label="手机号" align="center" prop="phonenumber"/>
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <span>{{ scope.row.sex === 0 ? '男' : scope.row.sex === 1 ? '女' : '未知' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" prop="deptName"/>
      <el-table-column label="岗位" align="center" prop="postName"/>
      <el-table-column label="发布状态" align="center" prop="id">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_pubilsh_task" :value="scope.row.id !== null ? '1' : '0'"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleAdd(scope.row)"
            v-hasPermi="['publisher:task:add']"
          >发布
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['publisher:task:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['publisher:task:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务发布对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入任务标题"/>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item>
          <el-upload
            class="upload-demo"
            action="http://127.0.0.1:8080/file/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="handleSuccess"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单个文件不超过10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTask,
  getTask,
  delTask,
  addTask,
  updateTask,
  deleteFile,
  delFileMinio,
  upadtaFileId
} from "@/api/publisher/task"
import {allListDept} from "@/api/system/dept.js"


export default {
  name: "Task",
  dicts: ['is_pubilsh_task'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的用户id数组
      userIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 所有的部门
      allDept: [],
      // 总条数
      total: 0,
      // 任务发布表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        deptId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {required: true, message: "任务标题不能为空", trigger: "blur"}
        ],
        description: [
          {required: true, message: "任务描述不能为空", trigger: "blur"}
        ],
      },
      // 文件
      fileList: [],
      fileId: undefined, // 文件的id
      taskId: undefined,
      fileIds: undefined,// 多选文件id删除
    }
  },
  created() {
    this.getList()
    this.getAllDept()
  },
  methods: {
    // 查询部门信息
    getAllDept() {
      allListDept().then(res => {
        this.allDept = res.data
      })
    },
    /** 查询任务发布列表 */
    getList() {
      this.loading = true
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.fileList = []
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.userIds = selection.map(item => item.userId)
      this.fileIds = selection.map(item => item.fileId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.fileList = []
      this.fileId = undefined
      if (row.userId !== undefined) {
        this.userIds = []
        this.userIds.push(row.userId)
      }
      this.reset()
      this.open = true
      this.title = "添加任务发布"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      if (Array.isArray(id) && (id.length === 0 || id[0] == null)) {
        this.$message.error("请先添加任务再来修改")
        return false
      }
      this.fileList = []
      this.taskId = id
      getTask(id).then(response => {
        this.form = response.data
        if (response.data.fileId !== null) {
          this.fileList.push({
            name: response.data.originalName,
            url: response.data.url,
            fileName: response.data.fileName,
            fileId: response.data.fileId,
          })
          this.fileId = response.data.fileId
        }
        this.open = true
        this.title = "修改任务发布"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.fileId === undefined) {
              this.$message.error('你没有上传文件')
              return false
            }
            this.form.fileId = this.fileId
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            if (this.fileId !== undefined) {
              this.form.fileId = this.fileId
            } else {
              this.$message.error('你没有上传文件')
              return false
            }
            addTask(this.form, this.userIds).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const fileId = row.fileId || this.fileIds
      if (fileId == null || fileId.length === 0) {
        this.$message.warning('没有文件')
        return false
      }
      this.$modal.confirm('是否确认删除任务发布编号为"' + ids + '"的数据项？').then(function () {
        return delTask(ids, fileId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('publisher/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    },

    /** 文件列表移除文件时的钩子*/
    handleRemove(file, fileList) {
      if (file.response !== undefined) {
          delFileMinio(file.response.storedName).then(() => {
          })
      } else {
        delFileMinio(file.fileName).then(() => {
        })
        upadtaFileId(this.taskId).then(response => {
        })
      }
    },
    /** 点击文件列表中已上传的文件时的钩子*/
    handlePreview(file) {
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    /** 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。*/
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).then(() => {
        this.fileList = []
        this.fileId = undefined
      })
    },
    handleSuccess(response) {
      this.fileId = response.id
    }
  }
}
</script>
